package com.gjp.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by 郭金鹏 on 2017/5/30.
 */
@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Value("${fileUploadDir}")
    private String fileUploadDir;

    /**
     * 文件上传
     *
     * @param request
     * @param file     对应页面上input框的name属性
     * @return
     */
    @PostMapping("/upload")
    public String upload(HttpServletRequest request,MultipartFile[] file) {
        try {
            for (MultipartFile item : file){
                //上传文件
                executeUpload(request, item);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }

    private void executeUpload(HttpServletRequest request, MultipartFile file) throws IOException {

        //获取文件存储目录 (根目录为webapp目录)
        String uploadDir = request.getSession().getServletContext().getRealPath("/") + fileUploadDir;

        //如果目录不存在则创建
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdir();
        }

        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //上传文件名+后缀
        String fileName = UUID.randomUUID() + suffix;

        //创建文件对象
        File uploadFile = new File(uploadDir + fileName);

        //将文件上传到uploadDir目录下
        file.transferTo(uploadFile);
    }
}
